#!/usr/bin/python3
# coding=utf-8
import sys
import json


def iosdiagJoinData(raw):
    postprocess_result = {
        "code": 0,
        "err_msg": "",
        "result": {}
    }
    if raw.startswith('fail'):
        postprocess_result["code"] = 1
        postprocess_result["err_msg"] = f"Diagnosis failed:\n{raw}"
        print(json.dumps(postprocess_result, indent=4))
        return

    raw = raw.strip()
    disks = []
    stat = {}
    stat["disks"] = {"data": [{'key': 0, 'value': 'overview'}]}
    stat["iohangOverview_overview"] = {
        "data": [{'key': 'Check Result', "value": "normal"},
                 {'key': "Number of OS HANG", "value": 0},
                 {'key': "Number of Disk HANG", "value": 0}]}
    stat["summary"] = "diagnose results: Normal, No IO Hang"

    for s in raw.split('\n'):
        try:
            obj = json.loads(s)
        except Exception:
            continue
        dataSource = "singleIO_"
        if "percent" in str(obj):
            disks = [s['diskname'] for s in obj['summary']
                     if s['diskname'] not in disks]
            stat["disks"]["data"] = \
                [{'key': disks.index(d), 'value': d} for d in disks]
            dataSource = "iohangOverview_"
        for d in disks:
            if (dataSource+d) not in stat.keys():
                stat[dataSource+d] = {"data": []}
            for s in obj['summary']:
                if d in s['diskname']:
                    if "percent" not in str(obj):
                        s["hung ios"] = \
                            sorted(s["hung ios"],
                                   key=lambda e: float(
                                       e['abnormal'].split()[-2]),
                                   reverse=True)[:10]
                        stat[dataSource+d]["data"] = s["hung ios"]
                    else:
                        count = sum([io["count"] for io in s["hung ios"]])
                        status = "abnormal" if count else "normal"
                        dataOverview = [
                            {'key': 'Check for '+d, "value": status}]
                        maxCount = 0
                        maxDelayComp = ''
                        for io in s["hung ios"]:
                            dataOverview.append({
                                'key': "Number of "+io["component"]+" HANG",
                                "value": int(io["count"])})
                            if maxCount < int(io["count"]):
                                maxCount = int(io["count"])
                                maxDelayComp = io["component"]
                        stat[dataSource+d]["data"] = dataOverview

                        if 'Abnormal' not in stat["summary"]:
                            stat["summary"] = "diagnose results: Abnormal, "
                        stat["summary"] += \
                            ("The IO of disk %s is hang, caused by %s hang;" % (
                                d, maxDelayComp))
    postprocess_result["result"] = stat
    s = json.dumps(postprocess_result, indent=4)
    print(s)


def extract_params():
    path, res, task_id = sys.argv[1], "", sys.argv[2]
    with open(path, 'r') as tmp:
        res = tmp.read()
    return res, task_id


if __name__ == "__main__":
    res, _ = extract_params()
    iosdiagJoinData(res)
